import Vue from "vue";
import VueRouter from "vue-router";

// 进度条
import NProgress from "nprogress";
import "nprogress/nprogress.css";

import store from "@/store/index";
import util from "@/libs/util.js";
import { getToken } from "@/utils/auth";

// 路由数据
import routes from "./routes";
import { uniqueId } from "lodash";
import { frameInRoutes } from "@/router/routes";

import layoutHeaderAside from "@/layout/header-aside";
const _import = require("@/libs/util.import." + process.env.NODE_ENV);
// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return VueRouterPush.call(this, location).catch(err => err);
};
const VueRouterReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
  return VueRouterReplace.call(this, location).catch(err => err);
};

Vue.use(VueRouter);

// 导出路由 在 main.js 里使用
const router = new VueRouter({
  routes
});
/**
 * 路由拦截
 * 权限验证
 */
// 免校验token白名单
const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
  // 确认已经加载多标签页数据 https://github.com/d2-projects/d2-admin/issues/201
  await store.dispatch("d2admin/page/isLoaded");
  // 确认已经加载组件尺寸设置 https://github.com/d2-projects/d2-admin/issues/198
  await store.dispatch("d2admin/size/isLoaded");
  // 进度条
  NProgress.start();
  // 关闭搜索面板
  store.commit("d2admin/search/set", false);
  const hasToken = getToken();
    if (hasToken) {
      if (to.path === '/login') {
        next()
        NProgress.done()
      } else {
        if(store.getters.status==1||store.getters.status==null){
          store.dispatch("user/getInfo").then(res => {
            store.commit("SET_STATUS", 2);
            const ax = store.getters.menus;
            const menus = filterAsyncRouter(ax);
            menus.push({
              path: "*",
              name: "404",
              component: _import("system/error/404")
            });
            router.addRoutes(menus);
            router.options.routes = menus;
            var work = store.getters.menus;
            work.forEach(item => {
              if (item.children.length > 0) {
                item.children.forEach(i => {
                  i.path = "/" + i.name;
                  i.title = i.meta.title;
                  i.icon = i.meta.icon;
                });
              }
            });
            const objs = {};
            for (var i = 0; i < work.length; i++) {
              objs[work[i].name] = work[i];
            }
            function supplementPath(menu) {
              return menu.map(e => ({
                ...e,
                path: e.path || uniqueId("d2-menu-empty-"),
                ...(e.children
                  ? {
                      children: supplementPath(e.children)
                    }
                  : {})
              }));
            }
            const Arrays = [{ path: "/index", title: "首页", icon: "home" }];
            if (JSON.stringify(objs) != "{}") {
              for (var i in objs) {
                Arrays.push(objs[i]);
              }
            }
            const menuHeader = supplementPath(Arrays);
            let routerTitle = frameInRoutes.concat(store.getters.menus);
            store.commit("d2admin/page/init", routerTitle);
            store.commit("d2admin/menu/headerSet", menuHeader);
            store.commit("d2admin/search/init", menuHeader);
            next({
              ...to,
              replace: true
            });
          });
        }else{
          next()
        }
      }
    }else{
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        next({
          name: 'login',
          query: {
            redirect: to.fullPath
          }
        })
        NProgress.done()
      }


    }
  // 验证当前路由所有的匹配中是否需要有登录验证的
  // if (to.matched.some(r => r.meta.auth)) {
  // if (whiteList.indexOf(to.path) === -1) {
    // 这里暂时将cookie里是否存有token作为验证是否登录的条件
    // 请根据自身业务需要修改
    // const hasToken = getToken();
    // if (hasToken) {
      // if (sessionStorage.getItem("vue_admin_template_token")) {
      //   if(store.getters.status==1||store.getters.status==null){
      //   store.dispatch("user/getInfo").then(res => {
      //     store.commit("SET_STATUS", 2);
      //     const ax = store.getters.menus;
      //     const menus = filterAsyncRouter(ax);
      //     menus.push({
      //       path: "*",
      //       name: "404",
      //       component: _import("system/error/404")
      //     });
      //     router.addRoutes(menus);
      //     router.options.routes = menus;
      //     var work = store.getters.menus;
      //     work.forEach(item => {
      //       if (item.children.length > 0) {
      //         item.children.forEach(i => {
      //           i.path = "/" + i.name;
      //           i.title = i.meta.title;
      //           i.icon = i.meta.icon;
      //         });
      //       }
      //     });
      //     const objs = {};
      //     for (var i = 0; i < work.length; i++) {
      //       objs[work[i].name] = work[i];
      //     }
      //     function supplementPath(menu) {
      //       return menu.map(e => ({
      //         ...e,
      //         path: e.path || uniqueId("d2-menu-empty-"),
      //         ...(e.children
      //           ? {
      //               children: supplementPath(e.children)
      //             }
      //           : {})
      //       }));
      //     }
      //     const Arrays = [{ path: "/index", title: "首页", icon: "home" }];
      //     if (JSON.stringify(objs) != "{}") {
      //       for (var i in objs) {
      //         Arrays.push(objs[i]);
      //       }
      //     }
      //     const menuHeader = supplementPath(Arrays);
      //     let routerTitle = frameInRoutes.concat(store.getters.menus);
      //     store.commit("d2admin/page/init", routerTitle);
      //     store.commit("d2admin/menu/headerSet", menuHeader);
      //     store.commit("d2admin/search/init", menuHeader);
      //     // console.log(router)
      //     next({ ...to, replace: true });
      //   });
      // }else{
      //   // console.log(router)
      //   next();
      // }
      // } else {
      //   // next();
      //   next({
      //       name: "login",
      //       query: {
      //         redirect: to.fullPath
      //       }
      //     });
      //     NProgress.done();
      // }
      // console.log(to, from);
    // } else {
      // 没有登录的时候跳转到登录界面
      // 携带上登陆成功之后需要跳转的页面完整路径
      // next({
      //   name: "login",
      //   query: {
      //     redirect: to.fullPath
      //   }
      // });
      // https://github.com/d2-projects/d2-admin/issues/138
    //   NProgress.done();
    // }
  // } else {
    // 不需要身份校验 直接通过
    // next();
  // }
});

router.afterEach(to => {
  // 进度条
  NProgress.done();
  // 多页控制 打开新的页面
  store.dispatch("d2admin/page/open", to);
  // 更改标题
  util.title(to.meta.title);
});
function filterAsyncRouter(asyncRouterMap) {
  // console.log(asyncRouterMap)
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === "layoutHeaderAside") {
        route.component = layoutHeaderAside;
      } else {
        route.component = _import(route.component); // 导入组件
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children);
    }
    return true;
  });
  return accessedRouters;
}
export default router;
